package com.omuao.message.websocket.config;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MQTT 服务器客户端配置
 *
 * @author omuao
 */
@Configuration
public class MqttClientConfig {


    @Autowired
    MqttProperties mqttProperties;

    /**
     * MQTT 客户端
     *
     * @return
     * @throws MqttException
     */
    @Bean("mqttClient")
    public MqttClient mqttClient() throws MqttException {
        MqttDefaultFilePersistence persistence = new MqttDefaultFilePersistence();
        MqttClient client = new MqttClient(mqttProperties.getBrokerAddress(),
                mqttProperties.getSuperClientId(), persistence);
        return client;

    }

    @Bean("mqttConnectOptions")
    public MqttConnectOptions mqttConnectOptions() throws MqttException {
        // MQTT 连接选项
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(mqttProperties.getSuperUsername());
        mqttConnectOptions.setPassword(mqttProperties.getSuperPassword().toCharArray());
        // 保留会话
        mqttConnectOptions.setCleanSession(true);
        return mqttConnectOptions;
    }


}
